package com.feiyi.app.activity;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ActivityUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.feiyi.app.R;
import com.feiyi.app.adapter.GoodsSearchAdapter;
import com.feiyi.app.app.AppConstant;
import com.feiyi.app.base.BaseActivity;
import com.feiyi.app.bean.GoodsSearchBean;
import com.feiyi.app.net.HttpMethods;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.FormBody;
import okhttp3.RequestBody;

/**
 * 作者 : wlt
 * 创建时间:  2018-07-16
 * QQ : 1346947404
 * 邮箱:wanglt_android@163.com
 * 类说明:产品搜索界面,可以根据品牌搜索,也可以根据类别搜索
 * In me the tiger sniffs the rose
 */

public class GoodsSearchActivity extends BaseActivity {



    @BindView(R.id.back)
    ImageView back;

    @BindView(R.id.rl_search)
    RelativeLayout rl_search;

    @BindView(R.id.tv_zonghe)
    TextView tv_zonghe;

    @BindView(R.id.tv_xiaoliang)
    TextView tv_xiaoliang;
    @BindView(R.id.iv_sales_up)
    ImageView iv_sales_up;
    @BindView(R.id.iv_sales_down)
    ImageView iv_sales_down;

    @BindView(R.id.tv_jiage)
    TextView tv_jiage;

    @BindView(R.id.iv_price_up)
    ImageView iv_price_up;
    @BindView(R.id.iv_price_down)
    ImageView iv_price_down;

    @BindView(R.id.tv_shaixuan)
    TextView tv_shaixuan;

    @BindView(R.id.rv_goods_list)
    RecyclerView rv_goods_list;

    private List<GoodsSearchBean.DataBean> mList = new ArrayList<>();

    private GoodsSearchAdapter mAdapter;
    /**
     * 下面几个条件均为搜索条件
     * 传进来那个条件用哪个搜索
     * 目前仅用到了category_id和brand_id
     */
    private String 	keywords;
    private String 	category_id;
    private String 	price_max;
    private String 	price_min;
    private String 	brand_id;
    private String 	sort_by;
    /**
     * sort_by=is_new   按照最新排序
     =price_desc  价钱降序
     =price_asc  价钱升序
     =sale_desc 销售降序
     =sale_asc  销量升序
     */

    private static final String TAG = "GoodsSearchActivity";

    private PopupWindow popupWindow;

    private EditText et_min;//popupwindow里面的输入的最小值

    private EditText et_max;//popupwindow里面输入的最大值

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_search);
        ButterKnife.bind(this);
        initView();
        initAdapter();
        changeColors(0,1,1,1);
        getFilters();
        initData();
    }

    private void initView() {
        rv_goods_list.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("goods_id",mList.get(position).getGoods_id());
                ActivityUtils.startActivity(bundle,GoodsDetailActivityNew.class);
            }
        });
    }

    /**
     * 设置整个页面顶部四个筛选条件
     * @param fresh 新品是否被点击
     * @param sales 销量是否被点击
     * @param price 价格是否被点击
     * @param filter 筛选是否被点击
     */
    private void changeColors(int fresh,int sales,int price,int filter){

        if (fresh == 0){
            tv_zonghe.setTextColor(getResources().getColor(R.color.red));
        }else {
            tv_zonghe.setTextColor(getResources().getColor(R.color.black));
        }

        if (sales == 0){
            tv_xiaoliang.setTextColor(getResources().getColor(R.color.red));
        }else {
            tv_xiaoliang.setTextColor(getResources().getColor(R.color.black));
        }

        if (price == 0){
            tv_jiage.setTextColor(getResources().getColor(R.color.red));
        }else {
            tv_jiage.setTextColor(getResources().getColor(R.color.black));
        }

        if (filter == 0){
            tv_shaixuan.setTextColor(getResources().getColor(R.color.red));
        }else {
            tv_shaixuan.setTextColor(getResources().getColor(R.color.black));
        }

    }

    private void getFilters() {
        Intent intent = getIntent();
        if(null != intent.getStringExtra("keywords")){
            keywords = intent.getStringExtra("keywords");
        }
        if(null != intent.getStringExtra("category_id")){
            category_id = intent.getStringExtra("category_id");
        }
        if(null != intent.getStringExtra("price_max")){
            price_max = intent.getStringExtra("price_max");
        }
        if(null != intent.getStringExtra("price_min")){
            price_min = intent.getStringExtra("price_min");
        }
        if(null != intent.getStringExtra("brand_id")){
            brand_id = intent.getStringExtra("brand_id");
        }
        if(null != intent.getStringExtra("sort_by")){
            sort_by = intent.getStringExtra("sort_by");
        }
    }

    private void initData() {
        FormBody.Builder builder = new FormBody.Builder();
        if (null != keywords)
        builder.add("keywords",keywords);
        if (null != category_id)
        builder.add("category_id",category_id);
        if (null != price_min)
        builder.add("price_min",price_min);
        if (null != price_max)
        builder.add("price_max",price_max);
        if (null != brand_id)
        builder.add("brand_id",brand_id);
        if (null != sort_by){
//            Log.e(TAG, "initData: "+sort_by );
            builder.add("sort_by",sort_by);
        }
        builder.add("page","1");
        builder.add("count","100");
        RequestBody body = builder.build();

        HttpMethods.getInstance().info.getSearch(AppConstant.GOODS_SEARCH,body).
                subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<GoodsSearchBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        addDisposable(d);
                    }

                    @Override
                    public void onNext(GoodsSearchBean goodsSearchBean) {
                        Log.e(TAG, "onNext: 111" );
                        if (null != goodsSearchBean.getData()){
                            mList.addAll(goodsSearchBean.getData());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "获取搜索列表失败 "+e.toString() );
                    }

                    @Override
                    public void onComplete() {
                                mAdapter.notifyDataSetChanged();
                    }
                });
    }

    private void initAdapter() {

        mAdapter = new GoodsSearchAdapter(R.layout.item_home_goods,mList);
        rv_goods_list.setLayoutManager(new GridLayoutManager(this,2));
        rv_goods_list.setAdapter(mAdapter);

    }

    @OnClick({R.id.back,R.id.rl_zonghe,R.id.iv_sales_up,R.id.iv_sales_down,R.id.iv_price_up,R.id.iv_price_down, R.id.rl_shaixuan})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.back://返回按钮
                finish();
                break;
            case R.id.rl_zonghe://按照最新排序
                changeColors(1,0,0,0);
                sort_by = "is_new";
                initData();
                break;
            case R.id.iv_sales_up://销量升序排序
                iv_sales_up.setImageResource(R.mipmap.up_arrow_red);
                iv_sales_down.setImageResource(R.mipmap.down_arrow);
                sort_by = "sale_asc";
                initData();
                break;
            case R.id.iv_sales_down://销量降序排序
                iv_sales_up.setImageResource(R.mipmap.up_arrow);
                iv_sales_down.setImageResource(R.mipmap.down_arrow_red);
                sort_by = "sale_desc";
                initData();
                break;
            case R.id.iv_price_up://价格升序排序
                iv_price_up.setImageResource(R.mipmap.up_arrow_red);
                iv_price_down.setImageResource(R.mipmap.down_arrow);
                sort_by = "price_asc";
                initData();
                break;
            case R.id.iv_price_down://价格降序排序
                iv_price_up.setImageResource(R.mipmap.up_arrow);
                iv_price_down.setImageResource(R.mipmap.down_arrow_red);
                sort_by = "price_desc";
                initData();
                break;
            case R.id.rl_shaixuan://筛选
                initPopWindow();
                break;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        dispose();
    }

    private void initPopWindow(){
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_more_filter, null);
        popupWindow = new PopupWindow(popupWindowView,300 , ViewGroup.LayoutParams.MATCH_PARENT, true);
        //菜单背景色
        ColorDrawable dw = new ColorDrawable(0xffffffff);
        popupWindow.setBackgroundDrawable(dw);
        popupWindow.showAtLocation(getLayoutInflater().inflate(R.layout.activity_main, null), Gravity.RIGHT, 0, 10000);
        //设置背景半透明
        backgroundAlpha(0.5f);
        //关闭事件
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
                if (null != et_min.getText() && !et_min.getText().toString().isEmpty()){
                    price_min = et_min.getText().toString();
                }else {
                    price_min = "0";
                }
                if (null != et_max.getText().toString() && !et_max.getText().toString().isEmpty()){
                    price_max = et_max.getText().toString();
                }else {
                    price_max = "10000000";
                }

                initData();
            }
        });
        et_min = popupWindowView.findViewById(R.id.et_min_price);
        et_max = popupWindowView.findViewById(R.id.et_max_price);
        popupWindowView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                /*if( popupWindow!=null && popupWindow.isShowing()){
                    popupWindow.dismiss();
                    popupWindow=null;
                }*/
                // 这里如果返回true的话，touch事件将被拦截
                // 拦截后 PopupWindow的onTouchEvent不被调用，这样点击外部区域无法dismiss
                return false;
            }
        });
    }
    /**
     * 设置添加屏幕的背景透明度
     * @param bgAlpha
     */
    public void backgroundAlpha(float bgAlpha)
    {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }
}
